Skip to content

Fix accept() and existing socket descriptor wrapping while sockets are disabled - #548

Open
Boulea7 wants to merge 4 commits into
miketheman:mainfrom
Boulea7:ln-cx/pytest-socket-540-existing-fd
Open

Boulea7 wants to merge 4 commits into
miketheman:mainfrom
Boulea7:ln-cx/pytest-socket-540-existing-fd

Conversation

@Boulea7

@Boulea7 Boulea7 commented Oct 6, 2026 •

Copy link
Copy Markdown

Allow socket.socket(fileno=...) to wrap existing Internet socket descriptors while sockets are disabled, so a pre-existing listener can still accept connections. Ordinary Internet socket creation stays blocked, explicit Unix families still require the Unix opt-in, and host restrictions remain active.

The tests use normal plugin autoload, ordinary accept()/detach(), and real --disable-socket hooks across consecutive tests. Main at 49db7da is merged, including its fixture teardown changes and current dependencies. The latest review cleanups remove the unused subprocess working directory and assert SocketBlockedWarning alongside SocketBlockedError in both blocked socketpair cases.

Fixes #540.

Validation on 2026-10-26 with the current lock on Linux CPython 3.11.2:

  • The fileno tests have 12 passed and one Windows-only skip; DNS tests have 12 passed, and fixture teardown tests have 17 passed.
  • Full suite: 146 passed, one skipped, two failures. Unmodified main at 49db7da has 134 passed and the same two failures: the Google TCP connection times out, and localhost resolves an extra 127.0.1.1 that differs from the expected error string.
  • mypy src passes with locked mypy 2.4.0. Plugin statement and branch coverage is 100% on both trees. The default report, which includes tests, decreases from 99.8880% on main to 99.2157% here. The extra uncovered paths are the PR's existing Windows-only test skipped on Linux (five statements) and the descriptor helper's failure-only cleanup (one statement and one branch).

The complete mutation gate could not finish: statistics collection stops on the Google test failure. Pre-commit hooks and native Windows/macOS tests have not run locally for this update, and no new performance comparison was collected.

CI for this update has not yet been verified.

@codspeed

codspeed Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will improve performance by 40.84%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 1 improved benchmark
✅ 11 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_bench_host_from_connect_args_unix 26.7 µs 19 µs +40.84%

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing Boulea7:ln-cx/pytest-socket-540-existing-fd (714d55d) with main (1e9ef4f)

Open in CodSpeed

@miketheman miketheman left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for picking up #540, and for the care in these tests. The core idea is right: wrapping a descriptor that already exists doesn't open a new connection, so the guard shouldn't stop it. I'd like a few changes before merging.

CI failure

test_two_consecutive_tests_can_use_an_existing_local_listener fails on every job with Plugin already registered under a different name: socket. pytest-socket is already loaded through its entry point, so pytester.runpytest("-p", "pytest_socket", "-v") (tests/test_socket_fileno.py:267) registers it a second time. pytester.runpytest() is enough. With that change and main merged in, the full suite passes locally.

Unix sockets now get past --allow-unix-socket

The exemption at src/pytest_socket/init.py:135 allows every constructor call that passes a fileno. Some stdlib helpers create brand new sockets in C and only then wrap them that way. On macOS and Linux, with --disable-socket and no --allow-unix-socket, these now succeed where main raises SocketBlockedError:

  • socket.socketpair()
  • socket.fromfd(fd, socket.AF_UNIX, ...)
  • asyncio.new_event_loop(), whose self-pipe comes from socketpair()

Windows still blocks them, since its socketpair() is written in Python and calls socket(AF_INET, ...). So on POSIX only, the PR changes what --allow-unix-socket controls, while the README (lines 22 and 91-95) still presents that flag as the way to allow async event loops.

I'd rather keep the Unix gate on this path:

if (fileno is not None and not _is_unix_socket(family)) or (
    _is_unix_socket(family) and allow_unix_socket
):

I tried this against your branch: all tests pass, accept() on a TCP listener still works, and socketpair() and new_event_loop() are blocked by default and allowed with allow_unix_socket=True. One gap remains. socket.socket(fileno=fd) without a family arrives with family=-1, so a Unix fd wrapped that way still gets through. That seems acceptable to me, and simpler than inspecting the fd.

Please add a test that socket.socketpair() is blocked without --allow-unix-socket and works with it, so this can't flip again unnoticed.

Tests

  • The _AcceptFdListener._accept override and the fd_cleanup ExitStack hand-off (lines 23-66) override CPython's private socket._accept to close an fd that only leaks once the test has already failed. Plain listener.accept() and socket.socket(fileno=original.detach()) exercise the same behavior. Dropping the scaffolding also removes its copy inside the pytester source at line 223.
  • In test_wrapped_fd_respects_host_restrictions_and_closes_on_denial, please call _remove_restrictions() in the finally. Cleanup works today only because socket_allow_hosts() runs after disable_socket(), so the connect patch lands on the throwaway GuardedSocket class. In the other order the patch would outlive the test, because enable_socket() doesn't restore connect.
  • test_wrapping_an_existing_fd_keeps_dns_guards and the {} case of test_creating_a_socket_without_an_existing_fd_stays_blocked repeat coverage that tests/test_dns.py and tests/test_socket.py already have. The {"fileno": None} case is the new part, so keep that one.
  • Please keep the fd 0 test. It's the only test that fails if the condition regresses to if fileno:. It doesn't need the hand-built env (line 152), though: the script never starts pytest, so subprocess.run([sys.executable, "-c", script], stdin=subprocess.DEVNULL, timeout=10, check=True) is enough.
  • Optional, but it would match the report directly: #540 describes a server thread whose accept() runs while the guard is installed, like socketserver or the session httpserver fixture in tests/conftest.py. The pytester test installs the guard by hand in a fixture rather than through --disable-socket, so it doesn't go through the plugin's own hooks either.

main has moved since you opened this. #550 added SocketBlockedWarning, a UserWarning subclass, so your pytest.warns(UserWarning, ...) checks still pass, and merging main in applies cleanly.

I worked through this review with Claude Code, which helped reproduce the CI failure and compare the socketpair() and event loop behavior between main and this branch.

@miketheman miketheman added the bug Something isn't working label Oct 12, 2026
Signed-off-by: boulea7 <zln1905391059@163.com>
@Boulea7

Boulea7 commented Oct 13, 2026

Copy link
Copy Markdown
Author

Updated the fd guard to preserve the explicit Unix-family opt-in, with socketpair coverage for the POSIX behavior and Windows TCP fallback. The tests now use normal plugin autoload and ordinary accept/detach calls, clean up host restrictions with _remove_restrictions(), retain fd 0/None without a custom child environment, and exercise real --disable-socket hooks across consecutive tests. Current main is merged.

Local mypy src and the fd/DNS/hooks scope pass (34 passed, one Windows-only skip). The full suite has two failures also reproduced on unmodified main; full mutation statistics stop on the existing Google test, and pre-commit bootstrap could not fetch its hooks. The local host-helper benchmark median changed by +2.9%, which does not resolve the earlier CodSpeed CI report. The new Python Tests, CodSpeed, and zizmor runs require approval and have executed zero jobs; please approve those runs for the platform and CI results.

miketheman
miketheman previously approved these changes Oct 21, 2026

@miketheman miketheman left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working through all of that, @Boulea7. Every point from the last round is addressed, and the Windows socketpair() case is a nice addition I didn't ask for.

Approving, with a few small cleanups inline. Each has a suggestion you can add to a batch and commit in one go. Please apply them before we merge. I tried them against this head: the fileno tests pass with no stray warnings, and black, isort and flake8 are clean.

I worked through this review with Claude Code again, which helped check the suggestions against the branch.

Comment thread tests/test_socket_fileno.py Outdated
import sys
import textwrap
from contextlib import contextmanager
from pathlib import Path

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the cwd= below removed, nothing else uses Path.

Suggested change
from pathlib import Path


import pytest_socket
from pytest_socket import (
SocketBlockedError,

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the pytest.warns suggestions on the socketpair() tests below.

Suggested change
SocketBlockedError,
SocketBlockedError,
SocketBlockedWarning,

Comment thread tests/test_socket_fileno.py Outdated
""")
subprocess.run(
[sys.executable, "-c", script],
cwd=Path(pytest_socket.__file__).resolve().parents[1],

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The script only imports pytest_socket, which is installed in the environment, so the subprocess doesn't need a working directory.

Suggested change
cwd=Path(pytest_socket.__file__).resolve().parents[1],

Comment thread tests/test_socket_fileno.py Outdated
Comment on lines +173 to +176
with pytest.raises(SocketBlockedError):
first, second = socket.socketpair()
with first, second:
pass

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The blocked call emits a SocketBlockedWarning that ends up in the suite's warnings summary. Asserting it keeps the output clean. The with first, second: block can't run once socketpair() raises, so it can go.

Suggested change
with pytest.raises(SocketBlockedError):
first, second = socket.socketpair()
with first, second:
pass
with (
pytest.raises(SocketBlockedError),
pytest.warns(SocketBlockedWarning),
):
socket.socketpair()

Comment thread tests/test_socket_fileno.py Outdated
Comment on lines +197 to +200
with pytest.raises(SocketBlockedError):
first, second = socket.socketpair()
with first, second:
pass

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same change for the Windows variant.

Suggested change
with pytest.raises(SocketBlockedError):
first, second = socket.socketpair()
with first, second:
pass
with (
pytest.raises(SocketBlockedError),
pytest.warns(SocketBlockedWarning),
):
socket.socketpair()

@miketheman

Copy link
Copy Markdown
Owner

The branch can also use an update from main to ensure it's being run against the current test suite and dependencies

Signed-off-by: boulea7 <zln1905391059@163.com>
@Boulea7

Boulea7 commented Oct 26, 2026

Copy link
Copy Markdown
Author

Applied all five inline suggestions and merged main at 49db7da. The fileno tests pass locally (12 passed, one Windows-only skip), and mypy src passes with the current locked dependencies. The full suite has the same two failures reproduced on updated main. Plugin coverage remains 100%, while the default report including tests is 99.2157% versus main's 99.8880%, due to the Linux-skipped Windows case and failure-only descriptor cleanup. Current results and remaining local validation limits are in the PR description.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

disable_socket() also breaks socket.accept() on already-open listening sockets

2 participants